<?php

namespace app\admin\controller\agentsystem;

use app\common\controller\Backend;

use think\Controller;
use think\Request;
use app\admin\model\YWithdrawals;
use think\Db;
use app\admin\model\YAgency;

/**
 * @icon fa fa-circle-o
 */
class Withdrawals extends Backend
{
    
    /**
     * YWithdrawals模型对象
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('YWithdrawals');

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个方法
     * 因此在当前控制器中可不用编写增删改查的代码,如果需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('pkey_name'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
    
            //搜索条件
            $filter = $this->request->get("filter", '');
            $filter_arr = json_decode($filter,true);
            $map = [];
            foreach ($filter_arr as $key=>$val){
                if($key == 'addtime'){
                    $time_arr = explode(',', $filter_arr['addtime']);
                    $star = $this->getMilliDate($time_arr[0].' 0:0:0');
                    $end = $this->getMilliDate($time_arr[1].' 23:59:59');
                    if(empty($time_arr[0])){
                        $map['addtime'] = array('<=', $end);
                    }elseif(empty($time_arr[1])){
                        $map['addtime'] = array('>=', $star);
                    }else{
                        $map['addtime'] = array('between', [$star,$end]);
                    }
                }else{
                    $map[$key] = $val;
                }
            }
    

            $totalall = Db::name('y_withdrawals')->where($map)->sum('money');//总
            $totalmonth = Db::name('y_withdrawals')->where("FROM_UNIXTIME(addtime/1000,'%Y-%m') = date_format(now(),'%Y-%m')")->sum('money');//月
            $totalweek = Db::name('y_withdrawals')->where("FROM_UNIXTIME(addtime/1000,'%Y-%m-%d %H:%I:%S') > date_sub(now(),interval 7 day) ")->sum('money');//周
            $totaltoday = Db::name('y_withdrawals')->where("FROM_UNIXTIME(addtime/1000,'%Y-%m-%d') = date_format(now(),'%Y-%m-%d')")->sum('money');//今天 
            $statistics['totalall'] = $totalall?:0;
            $statistics['totalmonth'] =$totalmonth?:0;
            $statistics['totalweek'] =$totalweek?:0;
            $statistics['totaltoday'] =$totaltoday?:0;
            
            $total = $this->model
            ->where($map)
            ->order($sort, $order)
            ->count();
    
            $list = $this->model
            ->where($map)
            ->order($sort, $order)
            ->limit($offset, $limit)
            ->select();
    
            //处理数据
            $uid_arr = $map_user =$user_arr = [];
            foreach ($list as $val){
                $uid_arr[] = $val['uid'];
            }
            $map_user['uid'] = array('in',$uid_arr);
            $user_list = $this->selectTbale($this->GameDBConfig,'user',$map_user,'uid,nickname');//用户列表
            foreach ($user_list as $val){
                $user_arr[$val['uid']] = $val['nickname'];
            }
            foreach ($list as $key=>$val){
                $list[$key]['nickname'] = isset($user_arr[$val['uid']])?$user_arr[$val['uid']]:'-';
            }
            
            $result = array("total" => $total, "rows" => $list, "statistics"=>$statistics, "map"=>empty($map)?0:1);
    
            return json($result);
        }
        return $this->view->fetch();
    }
    
    /**
     * 提现详情
     * @param number $ids
     * @author violet
     */
    public function detail($ids=0){
        $row = YWithdrawals::get(['ID'=>$ids]);
        if(empty($row)){
            $this->error('不是有效的提现记录');
        }
        
        $row['nickname'] = Db::connect("GameDB")->table('user')->where(['uid'=>$row['uid']])->value('nickname');//游戏昵称
        $row['confirmID'] = Db::table('fa_admin')->where(['id'=>$row['confirmID']])->value('nickname');//管理员昵称
        $row['successID'] = Db::table('fa_admin')->where(['id'=>$row['successID']])->value('nickname');//管理员昵称
        
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    
    /**
     * 改变提现状态
     */
    public function setStatusValue($ids=0 ,$status=0){
        $obj = YWithdrawals::get(['ID'=>$ids]);
        if(empty($obj)){
            $this->error('请正确操作');
        }
        Db::startTrans();
        //确认操作
        if($status == 1){
            if($obj->getData('status') != 0){
                $this->error('不是待确认状态，不可执行确认操作');
            }
            $obj->status = $status;
            $obj->confirmtime = getMilliseconds();
            $obj->confirmID = $this->auth->id;

        }
        //转账操作
        if($status == 2){
            if($obj->getData('status') != 1){
                $this->error('不是已确认状态，不可执行转账操作');
            }
            $obj_agency = YAgency::get(['uid'=>$obj->uid]);
            $obj_agency->money = $obj_agency->money +  $obj->money;
            if($obj_agency->save() === false){
                Db::rollback();
                $this->error('帐号提现金额修改失败，请重试');
            }
            $obj->status = $status;
            $obj->successtime = getMilliseconds();
            $obj->successID = $this->auth->id;
        }
        if($obj->save() === false){
            Db::rollback();
            $this->error('操作失败，请重试');
        }
        Db::commit();
        $this->success('操作成功','/admin/agentsystem/withdrawals/index');
    }

}
